package com.github.fancyideas.exceptions.handler;

import com.github.fancyideas.exceptions.AppException;
import com.github.fancyideas.utils.ResultBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

    private static final String SERVER_ERROR = "javax.servlet.error.status_code";
    private static final String CODE = "code";
    private static final String MESSAGED = "message";
    private static final String DETAIL = "detail";
    private static final String FORWARD = "forward:/error";

    @ExceptionHandler(AppException.class)
    public String appExceptionHandler(AppException e, HttpServletRequest request) {
        request.setAttribute(SERVER_ERROR, 500);
        Map<String, Object> map = new HashMap<>();
        map.put(CODE, e.getErrorSign());
        map.put(MESSAGED, e.getErrorMsg());
        request.setAttribute(DETAIL, map);
        return FORWARD;
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {
        BindingResult bindingResult = ex.getBindingResult();
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getDefaultMessage() + ";";
        }
        logger.warn("违规参数:{}", ex);
        return new ResponseEntity<>(ResultBuilder.buildError(errorMessage), HttpStatus.BAD_REQUEST);
    }

}
